package com.fandou.airobot.ui.alarm

import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.blankj.utilcode.util.SizeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.example.alarmclockdemo.AlarmAdapter
import com.fandou.airobot.R
import com.fandou.airobot.database.Alarm
import com.fandou.airobot.database.AlarmConstants
import com.fandou.airobot.database.AlarmDatabase
import com.fandou.airobot.service.AlarmReceiver
import com.fandou.airobot.utils.MyFragmentUtilsWrapper
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.alarm_clock_fragment.*

/**
 * @author       Jm
 * @date         2020/6/249:46
 * @description  AlarmClockFragment
 */
class AlarmListFragment : Fragment(), BaseQuickAdapter.OnItemClickListener,
    BaseQuickAdapter.OnItemLongClickListener {

    private val TAG = AlarmListFragment::class.java.name

    private var mAdapter: AlarmAdapter? = null

    private lateinit var mViewModel: AlarmViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.alarm_clock_fragment, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    private fun init() {
//        mViewModel = ViewModelProvider.NewInstanceFactory().create(AlarmViewModel::class.java)
        mViewModel =
            ViewModelProviders.of(context as AppCompatActivity).get(AlarmViewModel::class.java)
        initView()
        initListener()
        observeList()
        observeAdd()
        observeAddFromVoice()
        observeUpdate()
        observeUpdateFromReceiver()
        setData()
    }

    private fun initView() {
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.addItemDecoration(SpacesItemDecoration(10, 12))
        mAdapter = AlarmAdapter()
        recyclerView.adapter = mAdapter
        mAdapter!!.onItemClickListener = this
        mAdapter!!.onItemLongClickListener = this
    }

    private fun initListener() {
        titleBar.setOnRightClickListener {

            if (context is AppCompatActivity) {
                if (context is AppCompatActivity) {
                    MyFragmentUtilsWrapper.addFromBottom(
                        (context as AppCompatActivity?)!!.supportFragmentManager,
                        AddAlarmFragment.newInstance(true, AlarmConstants.AlarmType.ALARM),
                        android.R.id.content
                    )
                }

//                if (NavHostFragment.findNavController(this).currentDestination?.id==R.id.aiRobotAlarmListFragment){
//                    NavHostFragment.findNavController(this).navigate(R.id.action_aiRobotAlarmListFragment_to_aiRobotAlarmAddFragment
//                        ,  Bundle().also {
//                            it.putBoolean("isAddMode", true)
//                            it.putInt("type", AlarmConstants.AlarmType.ALARM)
//                        }
//                    )
//                }
            }
        }

    }

    /**
     * Observe the alarm clock list
     */
    private fun observeList() {
        mViewModel.alarmsLiveData.observe(viewLifecycleOwner, Observer {
            setData()
        })
    }

    /**
     * Observe the alarm to addData when an alarm or a countdown  add success
     */
    private fun observeAdd() {
        mViewModel.addAlarmLiveData.observe(viewLifecycleOwner, Observer {
            mAdapter!!.addData(it)
            if (it.enable) {
                Log.d(TAG, "addAlarm 设置闹钟：id:" + it.id + "name:" + it.remark)
                AlarmReceiver.setReminderAlarm(context, it)
            } else {
                Log.d(TAG, "addAlarm 取消闹钟：id:" + it.id + "name:" + it.remark)
                AlarmReceiver.cancelReminderAlarm(context, it)
            }
            scroll2Bottom()
        })
    }

    /**
     *订阅从语音识别中添加的闹钟
     */
    private fun observeAddFromVoice() {
        LiveEventBus
            .get(Alarm::class.java.name, Alarm::class.java)
            .observe(this, Observer {
                mAdapter!!.addData(it)
                if (it.enable) {
                    Log.d(TAG, "voice_addAlarm 设置闹钟：id:" + it.id + "name:" + it.remark)
                    AlarmReceiver.setReminderAlarm(context, it)
                } else {
                    Log.d(TAG, "voice_addAlarm 取消闹钟：id:" + it.id + "name:" + it.remark)
                    AlarmReceiver.cancelReminderAlarm(context, it)
                }
                scroll2Bottom()
            })
    }

    /**
     * Observe the alarm to update when the database had changed
     */
    private fun observeUpdate() {
        mViewModel.updateAlarmLiveData.observe(viewLifecycleOwner, Observer {
            mAdapter!!.updateAlarm(it)
            if (it.enable) {
                Log.d(TAG, "updateAlarm设置闹钟：id:" + it.id + "json:" + Gson().toJson(it))
                AlarmReceiver.setReminderAlarm(context, it)
            } else {
                Log.d(TAG, "updateAlarm取消闹钟：id:" + it.id + "json:" + Gson().toJson(it))
                AlarmReceiver.cancelReminderAlarm(context, it)
            }
        })
    }

    /**
     * observe update alarm from receiver
     */
    private fun observeUpdateFromReceiver() {
        LiveEventBus.get(AlarmEvent.UPDATE, AlarmEvent::class.java).observe(this, Observer {
            Log.d("fuckyou", "observeUpdateFromReceiver:${Gson().toJson(it)}")
            mAdapter!!.updateAlarm(it.alarm)
        })
    }

    private fun setData() {
        try {
            val allAlarms = AlarmDatabase.getInstance().alarmDao().allAlarms
            if (allAlarms.isNotEmpty()) {
                mAdapter!!.setNewData(allAlarms)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val alarm = adapter!!.getItem(position) as Alarm
        MyFragmentUtilsWrapper.addFromBottom(
            (context as AppCompatActivity?)!!.supportFragmentManager,
            AddAlarmFragment.newInstance(false, alarm.alarmType, alarm),
            android.R.id.content
        )
    }

    override fun onItemLongClick(
        adapter: BaseQuickAdapter<*, *>?,
        view: View?,
        position: Int
    ): Boolean {
        //暂时支持单个删除，下面有时间加上批量删除
        val alarm = adapter!!.getItem(position) as Alarm
        AlertDialog.Builder(requireContext()).setMessage("您确定要删除这个闹钟吗?")
            .setNegativeButton("取消") { dialog, which -> dialog?.dismiss() }
            .setPositiveButton("确定") { dialog, which ->
                val deleteAlarm = AlarmDatabase.getInstance().alarmDao().deleteAlarm(alarm)
                if (deleteAlarm > 0) {
                    AlarmReceiver.cancelReminderAlarm(context, alarm)
                    mAdapter!!.deleteAlarm(alarm.id)
                }
            }.show()
        return false
    }

    /**
     * 滚动到底部
     */
    private fun scroll2Bottom() {
        if (mAdapter!!.itemCount > 0) {
            recyclerView.smoothScrollToPosition(mAdapter!!.itemCount - 1)
        }
    }


    //以下是原本在item中点击编辑 和 删除的功能，现在我提出改成“点击条目就是编辑。然后 长按删除” 所以注释 @data 2020/06/29
//    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
//        val alarm = adapter!!.getItem(position) as Alarm
//        when (view!!.id) {
//            R.id.tvDelete -> {
//                // TODO 替换成原有项目的确认提示框
//                // show confirm
//                AlertDialog.Builder(context!!).setMessage("您确定要删除吗?").setNegativeButton("取消") { dialog, which -> dialog?.dismiss() }
//                    .setPositiveButton("确定") { dialog, which ->
//                        val deleteAlarm = AlarmDatabase.getInstance().alarmDao().deleteAlarm(alarm)
//                        if (deleteAlarm > 0) {
////                            mViewModel.alarmsLiveData.value = AlarmDatabase.getInstance().alarmDao().allAlarms
//                            mAdapter!!.deleteAlarm(alarm.id)
//                        }
//                    }.show()
//            }
//
//            R.id.tvEdit -> {
//                MyFragmentUtilsWrapper.addFromBottom(
//                    (context as AppCompatActivity?)!!.supportFragmentManager,
//                    AddAlarmFragment.newInstance(false, alarm.alarmType, alarm),
//                    android.R.id.content
//                )
//            }
//        }
//    }

    companion object {
        /**
         * @param
         */
        @JvmStatic
        fun newInstance(): AlarmListFragment {
            return AlarmListFragment().also { fragment ->
                fragment.arguments = Bundle().also {
                    it.putString("params", "")
                }
            }
        }
    }

    internal class SpacesItemDecoration : ItemDecoration {
        private var space: Int

        /**
         * 这是针对ui设计，一些列表的第一个item都距离顶部导航栏一些距离
         */
        private var firstItemPaddingTopDp = 0

        constructor(space: Int) {
            this.space = space
        }

        constructor(spaceDp: Int, firstItemPaddingTopDp: Int) {
            space = spaceDp
            this.firstItemPaddingTopDp = firstItemPaddingTopDp
        }

        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            outRect.left = 0
            outRect.right = 0
            outRect.bottom = SizeUtils.dp2px(space.toFloat())
            // Add top margin only for the first item to avoid double space between items
            if (parent.getChildLayoutPosition(view) == 0) {
                outRect.top = SizeUtils.dp2px(space.toFloat())
            }

            //仅仅在不为0的时候设置
            if (firstItemPaddingTopDp != 0) {
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.top = SizeUtils.dp2px(firstItemPaddingTopDp.toFloat())
                }
            }
        }
    }
}

